#include "Home.h"

#include <QDateTime>
#include <QDebug>
#include <QFrame>
#include <QLabel>
#include <QPushButton>
#include <QResizeEvent>
#include <QTimer>

#include "ConstData.h"
#include "ConstNames.h"
#include "DeviceYclHelper.h"
#include "SvgController.h"
#include "System.h"
#include "database.h"
#include "define.h"
#include "ui_home.h"
static const QStringList buttonNames = {
    "SV1",  "SV2",  "SV3",  "SV4",  "SV5",  "SV6",  "SV7",  "SV8",  "SV9", "SV10", "SV11", "SV12",
    "SV13", "SV14", "SV15", "SV16", "SV17", "SV18", "SV19", "SV20", "M1",  "M2",   "M3",   "M4"};

const QString style_activate = "QLabel{background-color:#45b39d; color: #fff;}";
const QString style_normal = "QLabel{background-color:transparent; color: #b1cdd4;}";

Home::Home(QWidget* parent) : QWidget(parent), ui(new Ui::Home)
{
    ui->setupUi(this);
    initInfoLabel();
    initSvgDisplay();
    initConnections();
}

Home::~Home()
{
    clearValveButtons();  // 清理阀门按钮
    delete ui;
}

void Home::initInfoLabel()
{
    auto setTimeText = [this](const SystemInfo& info) {
        QString text = info.nextZeroCheckTime.isValid()
                           ? info.nextZeroCheckTime.toString("MM-dd HH:mm")
                           : "未设置";
        ui->nextZeroCheckTime->setText(text);
        text = info.nextStdCheckTime.isValid() ? info.nextStdCheckTime.toString("MM-dd HH:mm")
                                               : "未设置";
        ui->nextStdCheckTime->setText(text);
        text = info.nextCalibTime.isValid() ? info.nextCalibTime.toString("MM-dd HH:mm") : "未设置";
        ui->nextCalibTime->setText(text);
        text = info.nextSpikeRecoveryTime.isValid()
                   ? info.nextSpikeRecoveryTime.toString("MM-dd HH:mm")
                   : "未设置";
        ui->nextSpikeRecoveryTime->setText(text);
        text = info.nextCleanTime.isValid() ? info.nextCleanTime.toString("MM-dd HH:mm") : "未设置";
        ui->nextCleanTime->setText(text);
    };
    connect(System::instance(), &System::infoChanged, this,
            [this, setTimeText](const SystemInfo& info) {
                if (System::instance()->isRunning()) {
                    setTimeText(info);
                }
            });
    connect(System::instance(), &System::isRunningChanged, this,
            [this, setTimeText](bool isRunning) {
                if (isRunning) {
                    setTimeText(System::instance()->getInfo());
                } else {
                    ui->nextZeroCheckTime->setText("---");
                    ui->nextStdCheckTime->setText("---");
                    ui->nextCalibTime->setText("---");
                    ui->nextSpikeRecoveryTime->setText("---");
                    ui->nextCleanTime->setText("---");
                }
            });
}

void Home::initSvgDisplay()
{
    ui->frame_main->setStyleSheet("QFrame{border-image: none;}");
    // 获取SVG控制器单例
    m_svgController = SvgController::getInstance();

    // 在QFrame中创建QLabel来显示SVG
    m_svgLabel = new QLabel(ui->frame_main);

    // 设置QLabel属性，但暂时不设置几何位置
    m_svgLabel->setScaledContents(true);  // 自动缩放内容
    m_svgLabel->setAlignment(Qt::AlignCenter);
    m_svgLabel->show();  // 确保标签可见

    // 将SVG标签移到最底层，这样其他控件可以显示在上面
    m_svgLabel->lower();
}

void Home::initConnections()
{
    // 当SVG更新时自动刷新显示
    connect(m_svgController, &SvgController::svgUpdated, this, &Home::updateSvgDisplay);

    // 连接异步渲染完成信号
    connect(m_svgController, &SvgController::pixmapReady, this, &Home::onPixmapReady);
    connect(m_svgController, &SvgController::renderError, this, &Home::onRenderError);

    // 当前系统状态
    ui->label_state_0->setStyleSheet(style_activate);
    IDevice* device = DeviceManager::instance()->getDeviceHelper("预处理");
    connect(device, &IDevice::deviceDataChanged, this, [this](const DeviceData& data) {
        m_svgController->updateTextInSvg(
            "pressure-text", QString::number(data.pressure_lastResult, 'f', 1));  // 压力
        updateSystemState(data.ycl_step_state);
        updateValveState(data.valveStatus);  // 阀门状态
    });

    // 常规设备数值及状态显示
    for (int i = 0; i < 4 && i < DEVICE_NAMES.size(); i++) {
        auto deviceName = DEVICE_NAMES[i];
        auto helper = DeviceManager::instance()->getDeviceHelper(DEVICE_NAMES[i]);
        if (helper && DEVICE_MAP[deviceName].deviceType == DeviceType_normal) {
            connect(helper, &IDevice::commStatusChanged, this, [this, i](const bool& commStatus) {
                if (!commStatus) {
                    QString componentId = "state-rect-" + QString::number(i + 1);
                    m_svgController->setComponentColor(componentId, "rgb(243, 52, 62)");
                    componentId = "state-text-" + QString::number(i + 1);
                    m_svgController->updateTextInSvg(componentId, "通讯失败");
                }
            });
            connect(helper, &IDevice::deviceDataChanged, this,
                    [this, i, helper](const DeviceData& data) {
                        updateDeviceData(helper, i + 1, data);
                    });
        }
    }
}

void Home::resizeEvent(QResizeEvent* event)
{
    QWidget::resizeEvent(event);

    // 窗口大小改变时，同时更新SVG标签的几何位置
    if (m_svgLabel && ui->frame_main) {
        m_svgLabel->setGeometry(ui->frame_main->rect());
        m_svgLabel->lower();  // 确保SVG保持在底层
        updateSvgDisplay();

        // 重新创建阀门按钮以适应新的尺寸
        // if (!m_valveButtons.isEmpty()) {
        QTimer::singleShot(50, this, &Home::createValveButtons);
        // }
    }
}

void Home::showEvent(QShowEvent* event)
{
    QWidget::showEvent(event);

    // 在窗口显示后设置SVG标签的几何位置和更新显示
    if (m_svgLabel && ui->frame_main) {
        m_svgLabel->setGeometry(ui->frame_main->rect());
        m_svgLabel->lower();  // 确保SVG保持在底层
        updateSvgDisplay();

        // 延迟创建阀门按钮，确保SVG已经正确显示
        QTimer::singleShot(100, this, &Home::createValveButtons);
    }

    // 启动设备数据监控
    startDataMonitoring();
}

void Home::hideEvent(QHideEvent* event)
{
    QWidget::hideEvent(event);

    // 停止设备数据监控
    // stopDataMonitoring();
}

void Home::updateSvgDisplay()
{
    if (!m_svgLabel || !m_svgController || this->isHidden()) {
        return;
    }

    // 获取QFrame的尺寸作为渲染尺寸
    QSize frameSize = ui->frame_main->size();
    if (frameSize.isEmpty()) {
        frameSize = QSize(800, 600);  // 默认尺寸
    }

    // 尝试异步渲染，如果失败则回退到同步渲染
    QString requestId = QString("home_update_%1").arg(QDateTime::currentMSecsSinceEpoch());
    m_svgController->getPixmapAsync(frameSize, requestId);
}

void Home::updateSvgDisplaySync()
{
    if (!m_svgLabel || !m_svgController) {
        return;
    }

    // 获取QFrame的尺寸作为渲染尺寸
    QSize frameSize = ui->frame_main->size();
    if (frameSize.isEmpty()) {
        frameSize = QSize(800, 600);  // 默认尺寸
    }

    // 同步获取SVG图像（原有逻辑）
    QPixmap pixmap = m_svgController->getPixmap(frameSize);
    if (!pixmap.isNull()) {
        m_svgLabel->setPixmap(pixmap);

        // 确保QLabel填充整个QFrame
        m_svgLabel->setGeometry(ui->frame_main->rect());
    } else {
        qWarning() << "SVG渲染失败";
    }
}

void Home::onPixmapReady(const QPixmap& pixmap, const QSize& requestedSize,
                         const QString& requestId)
{
    Q_UNUSED(requestedSize)
    Q_UNUSED(requestId)

    if (!pixmap.isNull() && m_svgLabel) {
        m_svgLabel->setPixmap(pixmap);

        // 确保QLabel填充整个QFrame
        m_svgLabel->setGeometry(ui->frame_main->rect());
    }
}

void Home::onRenderError(const QString& error, const QString& requestId)
{
    Q_UNUSED(requestId)

    qWarning() << "异步SVG渲染失败:" << error << "回退到同步渲染";

    // 回退到同步渲染
    updateSvgDisplaySync();
}

void Home::createValveButtons()
{
    // 先清理已有的阀门按钮
    clearValveButtons();

    if (!m_svgController || !ui->frame_main) {
        return;
    }

    // 获取SVG的显示尺寸和实际尺寸
    QSize frameSize = ui->frame_main->size();
    QSizeF svgSize = m_svgController->getPixmap().size();

    if (frameSize.isEmpty() || svgSize.isEmpty()) {
        qDebug() << "SVG尺寸或Frame尺寸无效，延后创建按钮";
        return;
    }

    // 计算缩放比例
    double scaleX = frameSize.width() / svgSize.width();
    double scaleY = frameSize.height() / svgSize.height();

    // 为已知的阀门创建按钮
    for (const QString& valveId : buttonNames) {
        // 获取阀门中心坐标
        QPointF center = m_svgController->getValveCenter(valveId);
        if (center == QPointF(-1, -1)) {
            continue;  // 该阀门不存在，跳过
        }

        // 根据缩放比例转换坐标
        int buttonX = (int)(center.x() * scaleX);
        int buttonY = (int)(center.y() * scaleY);

        // 创建按钮
        QPushButton* button = new QPushButton(ui->frame_main);
        button->setObjectName(valveId + "_button");
        button->setText("");
        button->setProperty("valveId", valveId);  // 存储阀门ID

        // 设置按钮大小（可根据需要调整）
        int buttonSize = 40;
        button->resize(buttonSize, buttonSize);

        // 居中对齐：按钮中心对准阀门中心
        button->move(buttonX - buttonSize / 2, buttonY - buttonSize / 2);

        // 连接点击信号
        connect(button, &QPushButton::clicked, this, &Home::onValveButtonClicked);

        button->show();
        m_valveButtons.append(button);
    }
}

void Home::clearValveButtons()
{
    // 删除所有阀门按钮
    for (QPushButton* button : m_valveButtons) {
        if (button) {
            button->deleteLater();
        }
    }
    m_valveButtons.clear();
}

void Home::updateSystemState(const quint16& status)
{
    const QString& state0 = status == VALVE_OP_IDLE ? style_activate : style_normal;
    const QString& state1 = status == VALVE_OP_EMPTY_WATER ? style_activate : style_normal;
    const QString& state2 = status == VALVE_OP_CLEAN ? style_activate : style_normal;
    const QString& state3 = status == VALVE_OP_DRAW_WATER ? style_activate : style_normal;
    const QString& state4 = status == VALVE_OP_UPPER_WATER ? style_activate : style_normal;
    const QString& state5 = status == VALVE_OP_CLEAN_ALGAE ? style_activate : style_normal;
    const QString& state6 = status == VALVE_OP_SETTLE ? style_activate : style_normal;
    ui->label_state_0->setStyleSheet(state0);  // 空闲
    ui->label_state_1->setStyleSheet(state1);  // 排空
    ui->label_state_2->setStyleSheet(state2);  // 清洗
    ui->label_state_3->setStyleSheet(state3);  // 抽水
    ui->label_state_4->setStyleSheet(state4);  // 配水
    ui->label_state_5->setStyleSheet(state5);  // 除藻
    ui->label_state_6->setStyleSheet(state6);  // 沉淀
}

void Home::updateValveState(const QVector<quint16>& valveStatus)
{
    for (int i = 0; i < valveStatus.size(); i++) {
        if (i < buttonNames.size()) {
            QString valveId = buttonNames[i];
            SvgController::ValveState state =
                valveStatus[i] ? SvgController::VALVE_OPEN : SvgController::VALVE_CLOSED;
            m_svgController->setValveState(valveId, state);
        }
    }
}

void Home::updateDeviceData(IDevice* device, int id, const DeviceData& data)
{
    QString positionId = "LB" + QString::number(id);
    QString text = QString::number(data.analyze_lastResult, 'f', 3);
    m_svgController->updateTextInSvg(positionId, text);
    if (data.status == 8) {
        m_svgController->setComponentColor("state-rect-" + QString::number(id), "rgb(9, 153, 57)");
        m_svgController->updateTextInSvg("state-text-" + QString::number(id), "空闲");
    } else {
        m_svgController->setComponentColor("state-rect-" + QString::number(id),
                                           "rgb(202, 184, 24)");
        m_svgController->updateTextInSvg("state-text-" + QString::number(id),
                                         device->getStatusName(data.status));
    }
}
void Home::onValveButtonClicked()
{
    QPushButton* button = qobject_cast<QPushButton*>(sender());
    if (!button) {
        return;
    }

    QString valveId = button->property("valveId").toString();
    if (valveId.isEmpty()) {
        return;
    }

    IDevice* device = DeviceManager::instance()->getDeviceHelper("预处理");
    if (!device || !device->isEnabled()) {
        showError("预处理", "设备未启用");
        return;
    }
    // 切换阀门状态
    SvgController::ValveState currentState = m_svgController->getValveState(valveId);
    qint16 addr = buttonNames.indexOf(valveId) + 1;
    if (addr == 0) {
        showError("预处理", "阀门ID错误" + valveId);
        return;
    }
    qint16 data = (currentState == SvgController::VALVE_OPEN) ? 0 : 1;
    device->control(addr, data);
    device->startDataMonitoring();  // 手动读一次数据，避免数据更新不及时
}

void Home::startDataMonitoring()
{
    // 常规设备
    for (int i = 0; i < 4 && i < DEVICE_NAMES.size(); i++) {
        auto deviceName = DEVICE_NAMES[i];
        auto helper = DeviceManager::instance()->getDeviceHelper(DEVICE_NAMES[i]);
        if (helper && helper->isEnabled() &&
            DEVICE_MAP[deviceName].deviceType == DeviceType_normal) {
            // helper->startDataMonitoring();
        } else {
            // 设置状态为未启用
            QString componentId = "state-rect-" + QString::number(i + 1);
            m_svgController->setComponentColor(componentId, " #9faab3");
            componentId = "state-text-" + QString::number(i + 1);
            m_svgController->updateTextInSvg(componentId, "未启用");
            componentId = "LB" + QString::number(i + 1);
            m_svgController->updateTextInSvg(componentId, "---");
        }
    }
}

void Home::stopDataMonitoring()
{
    auto system = System::instance();
    if (system->isRunning()) return;  // 如果系统在运行就不停止

    auto helper = DeviceManager::instance()->getDeviceHelper("预处理");
    if (helper) {
        helper->stopDataMonitoring();
    }
    // 常规设备
    for (int i = 0; i < 4 && i < DEVICE_NAMES.size(); i++) {
        auto deviceName = DEVICE_NAMES[i];
        auto helper = DeviceManager::instance()->getDeviceHelper(DEVICE_NAMES[i]);
        if (helper && DEVICE_MAP[deviceName].deviceType == DeviceType_normal) {
            helper->stopDataMonitoring();
        }
    }
}

void Home::on_pb_ycl_opt_clicked()
{
    operationWindow* opWindow = new operationWindow(this, "预处理", DisplayMode::Popup);
    opWindow->show();
}

void Home::on_pb_single_start_clicked()
{
    // 单次测量
    extern const int COMPOSITE_TASK_ANALYSIS;
    System::instance()->execTask(COMPOSITE_TASK_ANALYSIS);
}